#include "classload.h"

const char* ClassLoader::_class_path = NULL;

void ClassLoader::initialize(const char* class_path){
    _class_path = class_path; 
}

InstanceKlass *ClassLoader::load_classfile(const char *h_name) {
    
    char* file_name = (char*)malloc(1024);
     // construct full path name
    sprintf(file_name,"%s/%s.class",_class_path,h_name);

    printf("load class ===> %s\n", file_name);

    ClassFileStream *stream = NULL;
    InstanceKlass* klass = NULL;

    // check if file exists
    int file_handle;
    struct stat st;
    if (stat(file_name, &st) == 0) {
        void *buffer = alloca(st.st_size);
        file_handle = open(file_name, 0, 0);
        if (file_handle != -1) {
            ssize_t n = read(file_handle, buffer, st.st_size);
            if (n == st.st_size) {
                printf("content => %s\n ", (char*)buffer);
                stream = new ClassFileStream((u1*)buffer, st.st_size, file_name);
            }
            close(file_handle);
        }

    }

    if (stream != NULL) {
        ClassFileParser parser(stream);
        klass = parser.create_instance_klass();
    }

    return klass;
}
